<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12">
        <p class="text-subtitle-1 text-medium-emphasis">
          {{ $t('teacher.welcome', { name: authStore.userName, date: formattedDate }) }}
        </p>
      </v-col>
    </v-row>

    <!-- 我的班级概览 -->
    
            
            <div v-if="!loading && classStats.length === 0" class="text-center py-8">
              <v-icon size="64" color="grey">mdi-school-outline</v-icon>
              <p class="text-h6 mt-4">{{ $t('teacher.noClassAssigned') }}</p>
              <p class="text-body-2">{{ $t('teacher.contactAdmin') }}</p>
            </div>



    <!-- 今日统计 -->
    <v-row class="mb-6">
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('teacher.myTotalStudents')"
          :value="summary.total_students"
          icon="mdi-account-group"
          color="blue"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.presentToday')"
          :value="summary.present_count"
          icon="mdi-check-circle"
          color="green"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.leaveToday')"
          :value="summary.leave_count"
          icon="mdi-calendar-remove"
          color="orange"
        />
      </v-col>
      <v-col cols="12" sm="6" md="3">
        <StatCard
          :title="$t('dashboard.abnormalToday')"
          :value="summary.abnormal_count"
          icon="mdi-alert-circle"
          color="red"
        />
      </v-col>
    </v-row>  


  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { useSocketStore } from '@/stores/socket'
import StatCard from '@/components/StatCard.vue'

const router = useRouter()
const { t } = useI18n()
const authStore = useAuthStore()
const socketStore = useSocketStore()

// 响应式数据
const loading = ref(false)
const classStats = ref([])

// 计算属性
const formattedDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const summary = computed(() => {
  return classStats.value.reduce((acc, cls) => {
    acc.total_students += cls.total_students
    acc.present_count += cls.present_count
    acc.leave_count += cls.leave_count
    acc.abnormal_count += cls.abnormal_count
    return acc
  }, {
    total_students: 0,
    present_count: 0,
    leave_count: 0,
    abnormal_count: 0
  })
})

// 方法
const loadDashboardData = async () => {
  loading.value = true
  try {
    // 使用WebSocket获取教师仪表盘数据
    socketStore.socket.emit('get-teacher-dashboard', {
      teacherId: authStore.user?.id, // 修正为user.id
      userRole: authStore.userRole,
      date: new Date().toISOString().split('T')[0]
    })
  } catch (error) {
    console.error('加载教师仪表盘数据失败:', error)
    window.showNotification?.(t('common.loadDataFailed'), 'error')
    loading.value = false
  }
}

// WebSocket事件监听器
const setupSocketListeners = () => {
  if (!socketStore.socket) return
  
  // 监听教师仪表盘数据响应
  socketStore.socket.on('teacher-dashboard-data', (response) => {
    loading.value = false
    if (response.success) {
      classStats.value = response.data.classes || []
    } else {
      console.error('获取教师仪表盘数据失败:', response.message)
      window.showNotification?.(response.message || t('common.loadDataFailed'), 'error')
    }
  })
  
  // 监听学生状态更新
  socketStore.socket.on('student-status-updated', (data) => {
    // 实时更新班级统计数据
    loadDashboardData()
  })
}

// 清理WebSocket监听器
const cleanupSocketListeners = () => {
  if (!socketStore.socket) return
  
  socketStore.socket.off('teacher-dashboard-data')
  socketStore.socket.off('student-status-updated')
}



const getAttendanceColor = (rate) => {
  if (rate >= 90) return 'green'
  if (rate >= 80) return 'orange'
  return 'red'
}

const goToArrival = (classId) => {
  router.push({ name: 'ArrivalManagement', query: { classId } })
}

const goToDeparture = (classId) => {
  router.push({ name: 'DepartureManagement', query: { classId } })
}

const viewAllStudents = () => {
  // 查看所有学生（可以添加学生管理页面）
  window.showNotification?.(t('teacher.studentManagementInDevelopment'), 'info')
}



// 生命周期
onMounted(() => {
  setupSocketListeners()
  loadDashboardData()
})

onUnmounted(() => {
  cleanupSocketListeners()
})
</script>

<style scoped>
.class-card {
  transition: all 0.3s ease;
}

.class-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin: 16px 0;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 1.25rem;
  font-weight: bold;
}

.stat-label {
  font-size: 0.75rem;
  color: rgba(0, 0, 0, 0.6);
}

.text-blue { color: #2196f3; }
.text-green { color: #4caf50; }
.text-orange { color: #ff9800; }
.text-red { color: #f44336; }

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

